package cn.edu.lingnan.controllerV1;

import cn.edu.lingnan.service.QuestionStoreService;
import cn.edu.lingnan.service.UserService;
import cn.edu.lingnan.user.dtos.Result;
import cn.edu.lingnan.utils.AliOSSUtils;
import jakarta.websocket.server.PathParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private QuestionStoreService questionStoreService;
    /**
     * 上传头像
     * @param file
     * @param userId
     * @return
     * @throws IOException
     */
    @PostMapping("/upload_avatar")
    public Result upload(MultipartFile file, Long userId, String fileName) throws IOException {
        log.info("文件上传{},用户id{}",file.getOriginalFilename(),userId,fileName);
        String url=  aliOSSUtils.uploadAvatar(file,userId,fileName);//调用工具类上传文件
        log.info("文件上传完成：{}" ,url);
        userService.updateUserImage(userId,url);//更新用户头像
        log.info("用户头像更新完成：{},用户id：{}" ,url,userId);
        return Result.success(url);//返回路径
    }

    //删除图片
    @DeleteMapping("/delete_avatar")
    public Result deleteImg(@RequestParam("avatar") String  avatar){
        aliOSSUtils.delete(avatar);
        return Result.success();
    }
    @PostMapping("/upload_question_bank_img")
    public Result uploadBankImg(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "storeId", required = false) Long storeId,
            @RequestParam("fileName") String fileName) throws IOException {

        if (storeId != null) {
            log.info("题库图片上传：{}, 用户id：{}", file.getOriginalFilename(), storeId);
        } else {
            log.info("题库图片上传：{}, 用户id：未提供", file.getOriginalFilename());
        }

        String img = aliOSSUtils.uploadQuestionsStoreImg(file, storeId, fileName);
        log.info("题库图片上传完成：{}", img);

        if (storeId != null) {
            questionStoreService.updateUserQuestionBankImg(storeId, img); // 更新用户题库图片
        }

        return Result.success(img); // 返回路径
    }


}
